package org.dromara.web.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * TRTC 推流地址生成器
 *
 * @author Lion Li
 */
@Slf4j
public class TrtcPushUrlGenerator {

    /**
     * 生成推流地址
     *
     * @param roomId 房间ID
     * @param txTime 过期时间（秒）
     * @return 推流地址
     */
    public static String generatePushUrl(String roomId, String streamNamePrefix, long txTime, String pushDomain, String pushKey) {
        // 构建流名称
        String streamName = streamNamePrefix + roomId;

        // 将过期时间转换为十六进制
        String txTimeHex = Long.toHexString(txTime).toUpperCase();

        // 计算签名
        String input = pushKey + streamName + txTimeHex;
        String txSecret = DigestUtils.md5Hex(input);

        // 生成推流地址
        String pushUrl = String.format("rtmp://%s/live/%s?txSecret=%s&txTime=%s",
            pushDomain, streamName, txSecret, txTimeHex);

        log.info("生成的推流地址: {}", pushUrl);
        return pushUrl;
    }

    public static String generatePlayUrl(String roomId, String streamNamePrefix, long txTime, String playDomain, String playKey) {
        // 构建流名称
        String streamName = streamNamePrefix + roomId;

        // 将过期时间转换为十六进制
        String txTimeHex = Long.toHexString(txTime).toUpperCase();

        // 计算签名
        String input = playKey + streamName + txTimeHex;
        String txSecret = DigestUtils.md5Hex(input);

        // 生成推流地址
        String pushUrl = String.format("rtmp://%s/live/%s?txSecret=%s&txTime=%s",
            playDomain, streamName, txSecret, txTimeHex);

        log.info("生成的推流地址: {}", pushUrl);
        return pushUrl;
    }

    /**
     * 生成推流地址（使用默认过期时间24小时）
     *
     * @param roomId 房间ID
     * @return 推流地址
     */
    public static String generatePushUrl(String roomId, String streamNamePrefix, String pushDomain, String pushKey) {
        long txTime = System.currentTimeMillis() / 1000 + 24 * 3600; // 24小时后过期
        return generatePushUrl(roomId, streamNamePrefix, txTime, pushDomain, pushKey);
    }

    public static String generatePlayUrl(String roomId, String streamNamePrefix, String playDomain, String playKey) {
        long txTime = System.currentTimeMillis() / 1000 + 24 * 3600; // 24小时后过期
        return generatePlayUrl(roomId, streamNamePrefix, txTime, playDomain, playKey);
    }
}
